package report

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.myscrm.cn/golang/common/uuid"
	"gorm.io/gorm"
	"time"
)

type GfyxReportFollowRecordRepos struct {
	tenant_db.TenantDB
}

func NewGfyxReportFollowRecordRepos() GfyxReportFollowRecordReposIface {
	return &GfyxReportFollowRecordRepos{}
}

func (g *GfyxReportFollowRecordRepos) SaveReportFollowRecrod(ctx context.Context, data *GfyxReportFollowRecord) error {
	data.Uid = uuid.GetUUID()
	data.CreatedOn = time.Now()
	data.ModifiedOn = time.Now()
	db := g.GetTenantDB(ctx).Create(data)
	if db.Error != nil {
		return db.Error
	}
	return nil
}

func (g *GfyxReportFollowRecordRepos) GetReportFollowRecrod(ctx context.Context, reportId string, page int32, pageSize int32) ([]*GfyxReportFollowRecord, int64, error) {
	gfyxReportFollowRecordList := make([]*GfyxReportFollowRecord, 0)
	db := g.GetTenantDB(ctx).
		Where("is_deleted = 0 and report_id = ?", reportId).
		Order("created_on desc").
		Limit(int(pageSize)).
		Offset((int(page) - 1) * int(pageSize)).
		Find(&gfyxReportFollowRecordList)
	if db.Error != nil && db.Error != gorm.ErrRecordNotFound {
		return nil, 0, db.Error
	}
	total, err := g.getReportFollowRecrodTotal(ctx, reportId)
	if err != nil {
		return nil, 0, db.Error
	}
	return gfyxReportFollowRecordList, total, nil
}

func (g *GfyxReportFollowRecordRepos) getReportFollowRecrodTotal(ctx context.Context, reportId string) (int64, error) {
	var (
		total                  int64
		gfyxReportFollowRecord GfyxReportFollowRecord
	)
	db := g.GetTenantDB(ctx).
		Model(gfyxReportFollowRecord).
		Where("is_deleted = 0 and report_id = ?", reportId).
		Count(&total)
	if db.Error != nil && db.Error != gorm.ErrRecordNotFound {
		return 0, db.Error
	}
	return total, nil
}
